<?php

namespace app\controller;

use think\facade\Db;
use think\facade\View;

class Upsql
{
    public function index(){
        $dir="./updata";
            $lists =array();
            if (is_dir($dir))
            {
                ; //打开文件句柄
                if (( $resource = opendir($dir)) !==false){
                    while (($file = readdir($resource))!==false) //返回目录句柄中的条目
                    {
                        $newfile = $dir."/".$file;
//                echo is_dir($newfile);die();
                        if (is_dir($newfile) && $file!="."  && $file!="..")
                        {
                        }else{
                            if ($file =="."  || $file == "..")
                            {
                                continue;
                            }else{
                                //echo "文件:".$file."<br>";
                                array_push($lists,$file);
                            }
                        }
                    }
                    //return json($re);
                }
                closedir($resource);
            }else{
                return;
            }
        View::assign([
            'lists'=>$lists
        ]);
        return View::fetch();
    }
    public function add(){
        $to_file_name = "./updata/"."备份-".date("Y-m-d_H-i-s").".sql";
        $tabList = Db::connect()->getTables();
        //将每个表的表结构导出到文件

        foreach ($tabList as $val) {
            $sql = "show create table `" . $val . "`";
            $res = Db::query($sql);
            $info = "-- ----------------------------\r\n";
            $info .= "-- Table structure for `" . $val . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            $info .= "DROP TABLE IF EXISTS `" . $val . "`;\r\n";
            $sqlStr = $info . $res[0]['Create Table'] . ";\r\n\r\n";
            //追加到文件
            file_put_contents($to_file_name, $sqlStr, FILE_APPEND);
        }

//将每个表的数据导出到文件
        foreach ($tabList as $val) {
            $sql = "select * from `" . $val . "`";
            $res = Db::query($sql);
            //如果表中没有数据，则跳出循环
            if (count($res) < 1) continue;
            $info = "-- ----------------------------\r\n";
            $info .= "-- Records for `" . $val . "`\r\n";
            $info .= "-- ----------------------------\r\n";
            file_put_contents($to_file_name, $info, FILE_APPEND);
            //读取数据
            foreach ($res as $v) {
                $sqlStr = "INSERT INTO `" . $val . "` VALUES (";
                foreach ($v as $zd) {
                    $sqlStr .= "'" . $zd . "', ";
                }
                //去掉最后一个逗号和空格
                $sqlStr = substr($sqlStr, 0, strlen($sqlStr) - 2);
                $sqlStr .= ");\r\n";
                file_put_contents($to_file_name, $sqlStr, FILE_APPEND);
            }

            file_put_contents($to_file_name, "\r\n", FILE_APPEND);
        }
        echo json_encode(['code' => 0, 'msg' => '创建备份成功']);
    }
    public function up(){
        // 获取表单上传文件
        $file = request()->file('file');
        $to_file_name = "上传-".date("Y-m-d_H-i-s").".sql";
        // 上传到本地服务器
        $info = $file->move('./updata/',$to_file_name);
        //halt( $info);
        if($info){
            $res['code']=0;
            $res['msg'] = '上传成功！';
        }else{
            $res['code'] = 1;
            $res['msg'] = '上传失败！'.$file->getError();
        }
        return $res;
    }
    public function re(){
        $filename='./updata/'.input('get.filename');
        // 导入sql数据并创建表
        $bjyadmin_str=file_get_contents($filename);
        $sql_array=preg_split("/;[\r\n]+/", $bjyadmin_str);
        foreach ($sql_array as $k => $v) {
            if (!empty($v)) {
                Db::query($v);
            }
        }
        echo json_encode(['code' => 0, 'msg' => '恢复成功']);
    }
    public function down(){}
    public function del(){
        $filename='./updata/'.input('get.filename');
            if (!unlink($filename)){
                echo json_encode(['code' => 1, 'msg' => '删除失败']);
                exit;
            }else{
                echo json_encode(['code' => 0, 'msg' => '删除成功']);
                exit;
            }
    }
}
